package com.example.app3_1;

import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentTransaction;

public class HomeActivity extends AppCompatActivity {
    private static final String TAG = "HomeActivity";
    private static final String KEY_CURRENT_FRAGMENT = "current_fragment";
    private static final String KEY_USERNAME = "username";
    private static final String KEY_INTEREST = "interest";

    private String username;
    private String interest = "未选择";
    private int currentFragment = 0;

    private HomeFragment homeFragment;
    private ProfileFragment profileFragment;

    // 网络监听相关变量
    private ConnectivityManager connectivityManager;
    private ConnectivityManager.NetworkCallback networkCallback;
    private boolean isNetworkListenerStarted = false;
    private boolean currentNetworkAvailable = false;
    private long lastNetworkDialogTime = 0;
    private static final long MIN_DIALOG_INTERVAL = 5000; // 5秒内不重复弹窗

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        Log.d(TAG, "onCreate");

        // 恢复数据
        if (savedInstanceState != null) {
            username = savedInstanceState.getString(KEY_USERNAME);
            interest = savedInstanceState.getString(KEY_INTEREST, "未选择");
            currentFragment = savedInstanceState.getInt(KEY_CURRENT_FRAGMENT, 0);
        } else {
            // 从Intent获取数据
            Intent intent = getIntent();
            if (intent != null) {
                username = intent.getStringExtra("username");
            }
        }

        // 初始化Fragment
        homeFragment = HomeFragment.newInstance(interest);
        profileFragment = ProfileFragment.newInstance(username, interest);

        // 显示默认Fragment
        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.fragment_container, homeFragment)
                    .commit();
        }

        // 设置底部导航点击事件
        Button btnHome = findViewById(R.id.btn_home);
        Button btnProfile = findViewById(R.id.btn_profile);

        btnHome.setOnClickListener(v -> switchFragment(0));
        btnProfile.setOnClickListener(v -> switchFragment(1));

        // 恢复之前的Fragment状态
        if (savedInstanceState != null) {
            switchFragment(currentFragment);
        }

        // 登录成功后启动网络监听
        startNetworkListener();
    }

    /**
     * 启动网络状态监听
     */
    private void startNetworkListener() {
        if (isNetworkListenerStarted) {
            return;
        }

        connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);

        networkCallback = new ConnectivityManager.NetworkCallback() {
            @Override
            public void onAvailable(Network network) {
                super.onAvailable(network);
                Log.d(TAG, "网络已连接");
                currentNetworkAvailable = true;

                // 获取网络类型
                NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(network);
                String networkType = "未知网络";

                if (capabilities != null) {
                    if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
                        networkType = "Wi-Fi";
                    } else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
                        networkType = getMobileNetworkType(capabilities);
                    } else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)) {
                        networkType = "有线网络";
                    }
                }

                final String message = "网络已恢复\n连接类型：" + networkType;
                runOnUiThread(() -> {
                    showNetworkDialog(message);
                    // 通知Fragment网络状态变化
                    updateFragmentsNetworkStatus(true);
                });
            }

            @Override
            public void onLost(Network network) {
                super.onLost(network);
                Log.d(TAG, "网络已断开");
                currentNetworkAvailable = false;
                runOnUiThread(() -> {
                    showNetworkDialog("网络连接已断开");
                    // 通知Fragment网络状态变化
                    updateFragmentsNetworkStatus(false);
                });
            }

            @Override
            public void onCapabilitiesChanged(Network network, NetworkCapabilities capabilities) {
                super.onCapabilitiesChanged(network, capabilities);
                // 网络能力变化（如从4G切换到5G）
                if (capabilities != null && capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
                    String networkType = "未知网络";
                    if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
                        networkType = "Wi-Fi";
                    } else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
                        networkType = getMobileNetworkType(capabilities);
                    }

                    final String message = "网络类型变化\n当前连接：" + networkType;
                    runOnUiThread(() -> showNetworkDialog(message));
                }
            }
        };

        // 注册网络回调
        connectivityManager.registerDefaultNetworkCallback(networkCallback);
        isNetworkListenerStarted = true;
        Log.d(TAG, "网络监听已启动");

        // 初始化网络状态
        checkInitialNetworkStatus();
    }

    /**
     * 获取移动网络类型
     */
    private String getMobileNetworkType(NetworkCapabilities capabilities) {
        if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
            // 根据网络带宽等信息判断网络类型（简化版本）
            if (capabilities.getLinkDownstreamBandwidthKbps() > 100000) { // 100Mbps+
                return "5G网络";
            } else if (capabilities.getLinkDownstreamBandwidthKbps() > 10000) { // 10Mbps+
                return "4G网络";
            } else if (capabilities.getLinkDownstreamBandwidthKbps() > 1000) { // 1Mbps+
                return "3G网络";
            } else {
                return "2G网络";
            }
        }
        return "移动网络";
    }

    /**
     * 检查初始网络状态
     */
    private void checkInitialNetworkStatus() {
        NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(
                connectivityManager.getActiveNetwork());
        if (capabilities != null &&
                capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
            currentNetworkAvailable = true;
            updateFragmentsNetworkStatus(true);
            Log.d(TAG, "初始网络状态: 可用");
        } else {
            currentNetworkAvailable = false;
            updateFragmentsNetworkStatus(false);
            Log.d(TAG, "初始网络状态: 不可用");
        }
    }

    /**
     * 显示网络状态对话框
     */
    private void showNetworkDialog(String message) {
        long currentTime = System.currentTimeMillis();
        if (currentTime - lastNetworkDialogTime < MIN_DIALOG_INTERVAL) {
            Log.d(TAG, "跳过重复网络状态提示: " + message);
            return;
        }

        lastNetworkDialogTime = currentTime;

        runOnUiThread(() -> {
            try {
                new AlertDialog.Builder(HomeActivity.this)
                        .setTitle("网络状态变化")
                        .setMessage(message)
                        .setPositiveButton("确定", null)
                        .show();
            } catch (Exception e) {
                Log.e(TAG, "显示网络对话框失败: " + e.getMessage());
            }
        });
    }

    /**
     * 更新所有Fragment的网络状态
     */
    private void updateFragmentsNetworkStatus(boolean networkAvailable) {
        if (homeFragment != null && homeFragment.isAdded()) {
            homeFragment.updateNetworkStatus(networkAvailable);
        }
    }

    /**
     * 停止网络监听
     */
    private void stopNetworkListener() {
        if (connectivityManager != null && networkCallback != null) {
            try {
                connectivityManager.unregisterNetworkCallback(networkCallback);
                isNetworkListenerStarted = false;
                Log.d(TAG, "网络监听已停止");
            } catch (Exception e) {
                Log.e(TAG, "停止网络监听失败: " + e.getMessage());
            }
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "onStart");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "onResume");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "onStop");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy");

        // 停止网络监听，避免内存泄漏
        stopNetworkListener();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.d(TAG, "onRestart");
    }

    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString(KEY_USERNAME, username);
        outState.putString(KEY_INTEREST, interest);
        outState.putInt(KEY_CURRENT_FRAGMENT, currentFragment);
    }

    private void switchFragment(int fragmentIndex) {
        currentFragment = fragmentIndex;
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

        if (fragmentIndex == 0) {
            homeFragment = HomeFragment.newInstance(interest);
            transaction.replace(R.id.fragment_container, homeFragment);
        } else {
            profileFragment = ProfileFragment.newInstance(username, interest);
            transaction.replace(R.id.fragment_container, profileFragment);
        }

        transaction.commit();
    }

    public void updateInterest(String newInterest) {
        this.interest = newInterest;

        if (homeFragment != null && homeFragment.isAdded()) {
            homeFragment.updateInterest(newInterest);
        }
        if (profileFragment != null && profileFragment.isAdded()) {
            profileFragment.updateInterest(newInterest);
        }

        getSharedPreferences("UserData", MODE_PRIVATE)
                .edit()
                .putString("interest", newInterest)
                .apply();
    }

    public String getInterest() {
        return getSharedPreferences("UserData", MODE_PRIVATE)
                .getString("interest", interest);
    }

    public void showLogoutDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("确认退出");
        builder.setMessage("确定要退出登录吗？");
        builder.setPositiveButton("确定", (dialog, which) -> {
            logout();
        });
        builder.setNegativeButton("取消", (dialog, which) -> {
            dialog.dismiss();
        });
        builder.create().show();
    }

    private void logout() {
        // 退出登录时停止网络监听
        stopNetworkListener();

        // 清除自动登录信息
        getSharedPreferences("UserData", MODE_PRIVATE)
                .edit()
                .remove("autoLoginToken")
                .remove("autoLoginEmail")
                .putBoolean("autoLoginEnabled", false)
                .apply();

        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
        finish();
    }

    public void updateHomeFragmentInterest(String newInterest) {
        this.interest = newInterest;

        // 更新所有Fragment的兴趣显示 - 添加空检查
        if (homeFragment != null && homeFragment.isAdded()) {
            homeFragment.updateInterest(newInterest);
        }
        if (profileFragment != null && profileFragment.isAdded()) {
            profileFragment.updateInterest(newInterest);
        }

        // 保存到SharedPreferences，确保数据持久化
        getSharedPreferences("UserData", MODE_PRIVATE)
                .edit()
                .putString("interest", newInterest)
                .apply();
    }
}